Repository navigation
feat(wayland): add minimal Go Wayland client and protocol scanner - #210
Conversation
Reviewer's GuideData structuresDefine the Wayland runtime’s protocol metadata, object and connection state, and wire value types that underpin generated bindings and client behavior.
APIExpose core Wayland client bindings and the connection, dispatch, request, event, and codec APIs consumed by clients.
ImplementationImplement socket setup, object lifecycle, request transmission, event dispatch, and descriptor handling for the Linux client.
Implement Wayland wire encoding and decoding, argument validation, and descriptor ownership.
Implement optional client-side protocol tracing from environment settings and message metadata.
Implement XML parsing, validation, Go binding generation, and atomic output replacement in the protocol scanner.
ConfigurationAdd Wayland packages to build and test targets and include the client library in installation.
Provide the CMake helper and targets for generating core and optional extension bindings and running interop tests.
Add the scanner and runtime copyright/license metadata.
TestsExercise scanner rejection of invalid XML and name collisions, and verify output files are replaced atomically.
Test runtime descriptor delivery, retained array data, object destruction and ID reuse, and unhandled constructor events.
Exercise generated bindings against libwayland-server for wire types, versions, lifecycle, and tracing.
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
Hey - I've found 15 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="cmake/DDEAPI/DDEAPIWayland.cmake" line_range="41" />
<code_context>
+ add_custom_command(OUTPUT "${output}"
+ COMMAND "${CMAKE_COMMAND}" -E make_directory "${output_dir}"
+ COMMAND "${CMAKE_COMMAND}" -E env GOENV=off GO111MODULE=off CGO_ENABLED=0
+ --unset=GOOS --unset=GOARCH --unset=GOFLAGS
+ "${DDEAPI_GO_EXECUTABLE}" run "${scanner}" -package "${package}"
+ ${filter} -o "${output}" ${xml_files}
</code_context>
<issue_to_address>
**Binding generation command fails**
When a build executes a custom command created by `dde_generate_wayland_client`, `cmake -E env` parses the `--unset` options after the environment assignments as the command to execute, so it never launches Go and binding generation fails.
Move the `--unset` options before the environment assignments in the `cmake -E env` command.
</issue_to_address>
### Comment 2
<location path="wayland/CMakeLists.txt" line_range="15" />
<code_context>
+
+set(core "${CMAKE_CURRENT_BINARY_DIR}/core/wayland-client-protocol.go")
+dde_generate_wayland_client("${core}" core XML "${WAYLAND_CORE_XML}"
+ INTERFACES wl_display,wl_registry,wl_callback,wl_seat)
+set(bindings "${core}")
+if(WAYLAND_PROTOCOL_XML)
</code_context>
<issue_to_address>
**Seat child requests fail**
When a caller uses `WlSeat.GetPointer`, `GetKeyboard`, or `GetTouch` with the supplied core bindings, the generated core `Register` omits `wl_pointer`, `wl_keyboard`, and `wl_touch`, so `Object.Request` cannot find those interfaces and returns an unregistered-interface error instead of creating the requested object.
Include the pointer, keyboard, and touch interfaces in the generated core bindings.
Also at `wayland/core/wayland-client-protocol.go:163-174`.
</issue_to_address>
### Comment 3
<location path="Makefile" line_range="58" />
<code_context>
inhibit_hint \
powersupply \
polkit \
+ wayland \
ININSTALLS = \
</code_context>
<issue_to_address>
**Installed core package is missing**
When a downstream consumer installs the development files and imports `wayland/core`, `ININSTALLS` excludes `wayland/core`, so `install-dev` omits the package even though `build-dev` builds it, and the consumer cannot import the core bindings.
Add `wayland/core` to the development-package install list.
Also at `Makefile:137`.
</issue_to_address>
### Comment 4
<location path="wayland/conn_linux.go" line_range="271" />
<code_context>
+ if err != nil {
+ return err
+ }
+ c.fds = append(c.fds, fds...)
+ }
+ }
</code_context>
<issue_to_address>
**Child processes inherit Wayland descriptors**
When a received Wayland descriptor remains open while the process starts a child, `ReadMsgUnix` receives descriptors without close-on-exec, and `Conn.receive` queues them without setting that flag, so an exec'd child inherits the descriptors and can retain or access their resources.
Set close-on-exec on each received descriptor before it can be inherited by a child process.
Also at `wayland/conn_linux.go:256`.
</issue_to_address>
### Comment 5
<location path="wayland/wire_linux.go" line_range="19" />
<code_context>
+
+func (f Fixed) Float64() float64 { return float64(f) / 256 }
+
+const maxMessage = 4096
+
+var padding [3]byte
</code_context>
<issue_to_address>
**Valid large messages are rejected**
When a valid Wayland message or array exceeds 4 KiB, `Encoder` rejects outgoing messages above `maxMessage`, and `Conn.dispatch` rejects oversized incoming messages and closes the connection, so valid traffic larger than 4 KiB cannot be exchanged.
Remove the 4 KiB limit or raise it to the protocol's valid message-size limit.
Also at `wayland/conn_linux.go:304`.
</issue_to_address>
### Comment 6
<location path="wayland/conn_linux.go" line_range="326-327" />
<code_context>
+ d.closeFDs()
+ return fmt.Errorf("%s event %d: %w", o.spec.Name, opcode, err)
+ }
+ if event.Destructor {
+ o.destroy()
+ }
+ c.readAt += size
</code_context>
<issue_to_address>
**Destructor handlers send stale requests**
When a destructor-event listener sends a request on the object being destroyed, `Conn.dispatch` invokes `event.Decode` before `o.destroy()`, so the handler's `Object.Request` sees a live object and sends a request for an object the server has already destroyed.
Mark the object destroyed before invoking the destructor event handler.
</issue_to_address>
### Comment 7
<location path="cmd/go-wayland-scanner/main.go" line_range="377" />
<code_context>
+func emitRequest(b *bytes.Buffer, name string, op int, m message) {
+ var params, enc []string
+ result, binding, version := "error", `""`, "0"
+ for j, a := range m.Args {
+ v := fmt.Sprintf("arg%d", j)
+ if a.Type == "new_id" {
</code_context>
<issue_to_address>
**Unhandled new objects leak**
When an event containing `new_id` arrives without a registered listener, the generated decoder calls `d.NewID` before checking for a listener, which inserts the object into `Conn.objects`; when no listener is installed, the handle is discarded and the object remains registered without a way for the caller to destroy it.
Check for a listener before creating event `new_id` objects, or remove those objects when the event is unhandled.
Also at `cmd/go-wayland-scanner/main.go:378-379`, `wayland/wire_linux.go:177-178`.
</issue_to_address>
### Comment 8
<location path="cmd/go-wayland-scanner/main.go" line_range="290" />
<code_context>
+ }
+ if a.Type == "new_id" {
+ newIDs++
+ if newIDs > 1 || (event && a.Interface == "") {
+ return fmt.Errorf("%s: invalid new_id", m.Name)
+ }
</code_context>
<issue_to_address>
**Valid multiple-object messages are rejected**
When a valid protocol message contains more than one `new_id` argument, `validate` rejects the second `new_id`, so the scanner emits no bindings for these protocols; the generated API and runtime also support returning only one object, preventing callers from using them.
Allow multiple `new_id` arguments and generate runtime and API support for returning each created object.
</issue_to_address>
### Comment 9
<location path="cmd/go-wayland-scanner/main.go" line_range="306-308" />
<code_context>
+ if a.Type == "new_id" {
+ result = "(*wl.Object, error)"
+ if a.Interface == "" {
+ params = append(params, "interfaceName string", "version uint32")
+ binding, version = "interfaceName", "version"
+ enc = append(enc, "e.String(interfaceName)", "e.Uint(version)")
+ } else {
+ binding = fmt.Sprintf("%q", a.Interface)
</code_context>
<issue_to_address>
**Dynamic bindings encode duplicate arguments**
When a protocol request has an untyped `new_id` alongside its XML `interface` and `version` arguments, as `wl_registry.bind` does, `emitRequest` keeps the XML `interface` and `version` arguments, then adds another pair when it encounters an untyped `new_id`; the generated method sends both pairs, so a standard `wl_registry.bind` request has the wrong wire layout and the server rejects it.
Use the XML interface and version arguments as the dynamic binding inputs instead of adding and encoding a second pair.
</issue_to_address>
### Comment 10
<location path="wayland/conn_linux.go" line_range="291" />
<code_context>
+ n, err = c.sock.Write(e.data)
+ }
+ if err != nil || n != len(e.data) {
+ _ = c.Close()
+ if err == nil {
+ err = io.ErrShortWrite
</code_context>
<issue_to_address>
**Read timeout closes the connection**
When a caller sets a deadline and it expires while `Dispatch` waits for an event, `Conn.Dispatch` closes the socket for every dispatch error, including a recoverable deadline timeout; callers cannot extend the deadline and resume reading on the same connection.
Handle timeout errors separately from fatal protocol or socket errors, preserving any partial input so dispatch can resume after the deadline is extended.
</issue_to_address>
### Comment 11
<location path="wayland/conn_linux.go" line_range="146" />
<code_context>
+// DeleteID handles wl_display.delete_id. An ID cannot be reused until the
+// server has acknowledged its destruction.
+func (c *Conn) DeleteID(id uint32) {
+ if o := c.objects[id]; id > 1 && id < serverID && o != nil && o.dead {
+ delete(c.objects, id)
+ c.free = append(c.free, id)
</code_context>
<issue_to_address>
**Server-deleted objects remain usable**
When the server destroys a client-created object and sends `wl_display.delete_id` before the client has marked that object dead, `Conn.DeleteID` ignores the ID because `o.dead` is false, leaving the object registered and its ID unreusable. `Object.Request` can then send requests through the stale object, and the caller sees a protocol error while the ID remains leaked.
On a valid `delete_id`, mark the object dead, remove it from `c.objects`, and add its ID to `c.free` exactly once, even when it was not already dead.
</issue_to_address>
### Comment 12
<location path="cmd/go-wayland-scanner/main.go" line_range="249" />
<code_context>
+ fmt.Fprintf(b, "const %s = %s\n", constant, v.Value)
+ }
+ }
+ methods := map[string]string{"Object": "embedded Wayland object"}
+ for op, m := range i.Requests {
+ if err := validate(m, i.Version, false); err != nil {
</code_context>
<issue_to_address>
**Generated requests shadow runtime methods**
When a protocol contains a request named `version`, `on`, or `handler`, `emitInterface` allows requests named `version`, `on`, or `handler`, so the generated methods shadow the embedded `wl.Object` methods `Version`, `On`, and `Handler`; callers then cannot use those runtime methods through the generated wrapper as expected.
Reserve the embedded runtime method names when validating generated request and event-handler names, or generate wrappers that avoid shadowing them.
</issue_to_address>
### Comment 13
<location path="cmake/DDEAPI/DDEAPIWayland.cmake" line_range="44" />
<code_context>
+ --unset=GOOS --unset=GOARCH --unset=GOFLAGS
+ "${DDEAPI_GO_EXECUTABLE}" run "${scanner}" -package "${package}"
+ ${filter} -o "${output}" ${xml_files}
+ DEPENDS "${scanner}" ${xml_files}
+ VERBATIM)
+endfunction()
</code_context>
<issue_to_address>
**Changed generator settings leave stale bindings**
When a downstream project changes the package or interface filter and reconfigures with a Make-based CMake generator, make-based CMake builds do not track changes to custom-command arguments as dependencies, so changing `package` or `INTERFACES` leaves the existing output untouched when the scanner and XML files are unchanged. The build then compiles bindings generated with the old settings.
Make changes to the package and interface-filter settings invalidate the generated output, for example by depending on a configuration stamp that updates when those values change.
</issue_to_address>
### Comment 14
<location path="cmd/go-wayland-scanner/main.go" line_range="411" />
<code_context>
+ if *output == "" {
+ _, err = b.WriteTo(os.Stdout)
+ } else {
+ err = os.WriteFile(*output, b.Bytes(), 0644)
+ }
+ }
</code_context>
<issue_to_address>
**Interrupted generation leaves partial bindings**
When generation is interrupted or the output write fails after truncating the destination, `os.WriteFile` truncates the destination before writing; a write failure or interruption leaves a partial output file. A subsequent incremental Make build can treat that newer file as up to date and skip regeneration, leaving consumers with broken bindings.
Write the complete output to a temporary file and atomically rename it over the destination only after the write succeeds.
</issue_to_address>
### Comment 15
<location path="wayland/testdata/interop/client.go" line_range="119" />
<code_context>
+ return probe.SendValues(-123, flags, -320, "布局!", &empty, pattern, child, child, fd)
+ })
+ check(d.Roundtrip())
+ expect(values == 2 && serverEvents == 1 && arrays[0][0] == 9, "ordered callbacks or array ownership")
+ sendFD(serverChild.ExchangeFd)
+ check(d.Roundtrip())
</code_context>
<issue_to_address>
**Array aliasing passes interop test**
When both values events arrive in one socket read, `wayland-client-interop` mutates the first array at `client.go:97` and checks it at `client.go:119`, but if both events arrive in one socket read, a zero-copy decoder still points at untouched buffered bytes. The assertion passes without detecting that array data stops being independently owned.
Force a subsequent receive that reuses or compacts the input buffer before checking the retained array, and assert that its contents remain unchanged.
</issue_to_address>52a6d12 to
06d9cc5
Compare
1. Add a pure Go Wayland client with core bindings and opt-in protocol tracing. 2. Generate Go client bindings from protocol XML and replace output files atomically. 3. Add standalone CMake generation and cover wire interoperability and object lifecycle. Log: Add the Go Wayland client runtime and protocol scanner. Influence: Go clients can connect to Wayland compositors. feat(wayland): 新增 Go 客户端和协议生成器 1. 新增纯 Go Wayland 客户端,提供核心协议绑定和可选的协议日志。 2. 从协议 XML 生成 Go 客户端绑定,并原子替换输出文件。 3. 提供独立的 CMake 生成入口,覆盖协议互通和对象生命周期测试。 Log: 新增 Go Wayland 客户端运行时和协议生成器。 PMS: BUG-377251 Influence: Go 客户端可连接 Wayland 合成器。
06d9cc5 to
1fd5e0b
Compare
1. Keep protocol error reporting and object ID recycling when registering listeners. 2. Test that user listeners still run and bookkeeping is preserved. Log: Preserve internal display event handling when clients register listeners. Influence: Listeners retain error and ID handling. fix(wayland): 保留显示对象的内部事件处理 1. 注册监听器时保留协议错误上报与对象 ID 回收。 2. 验证用户回调和内部处理都能执行。 Log: 注册监听器时保留显示对象的内部事件处理。 PMS: BUG-377251 Influence: 监听器不会覆盖错误上报和 ID 回收。
|
[APPROVALNOTIFIER] This PR is NOT APPROVED This pull-request has been approved by: fly602, mhduiy The full list of commands accepted by this bot can be found here. DetailsNeeds approval from an approver in each of these files:Approvers can indicate their approval by writing |
Add a minimal Go Wayland client (connection, wire codec, core protocol bindings) under
wayland/, pluscmd/go-wayland-scanner— a code generator that turns a Wayland protocol XML into Go request/event bindings — and a CMake helper (dde_generate_wayland_client) so downstream consumers can generate bindings for their own protocols at build time.No existing packages depend on this yet; it is additive only.
Summary by Sourcery
Add a Go Wayland client and protocol-binding generation tools for core and downstream protocols.
New Features:
Build:
Tests:
Chores: